<template>
  <div class="pdf-file">
    <div class="tools" v-if="!loading">
      <div class="pdf-total-num">{{ pageNum }} / {{ pageTotalNum }}</div>

      <el-button-group class="button-group">
        <el-button icon="el-icon-arrow-left" size="mini" @click="onPrePage">上一页</el-button>
        <el-button icon="el-icon-arrow-right" size="mini" @click="onNextPage">下一页</el-button>
      </el-button-group>
    </div>

    <el-scrollbar v-loading="loading" class="pdf-content">
      <PDF
        :page="pageNum"
        :src="fileSrc"
        @progress="loadedRatio = $event"
        @num-pages="pageTotalNum = $event"
        @loaded="pageNum = 1"
      ></PDF>
    </el-scrollbar>
  </div>

</template>

<script>
import PDF from 'vue-pdf';
import { getObjectURL } from '@/utils/file';

export default {
  name: 'pdf-file',
  components: { PDF },
  props: ['file', 'loading'],
  data() {
    return {
      pageNum: 1, // 当前页
      pageTotalNum: 1,  // 总页数
      loadedRatio: 0, // 当前页面加载进度，范围是 0 - 1,等于1的时候代表当前页已经完全加载完成
      fileSrc: '',
    };
  },
  watch: {
    file: {
      handler(val) {
        if (val) {
          this.fileSrc = getObjectURL(val);
        }
      },
      immediate: true,
    },
  },

  methods: {
    /**
     * 上一页
     */
    onPrePage() {
      let page = this.pageNum;
      page = page > 1 ? page - 1 : this.pageTotalNum;
      this.pageNum = page;
    },

    /**
     * 下一页
     */
    onNextPage() {
      let page = this.pageNum;
      page = page < this.pageTotalNum ? page + 1 : 1;
      this.pageNum = page;
    },
  },
};
</script>

<style lang="scss" scoped>
.pdf-file {
  width: 100%;
  height: 100%;
  position: relative;

  .tools {
    display: flex;
    justify-content: space-between;
    align-items: center;
    height: 38px;
    width: 100%;
    z-index: 1;
    background-color: #fff;
    padding-bottom: 6px;
    border-bottom: 1px solid #ddd;

    .pdf-total-num {
      color: #409eff;
    }

    .button-group {
    }
  }

  .pdf-content {
    width: 100%;
    height: calc(100% - 40px);
  }

  ::v-deep .el-scrollbar__wrap {
    overflow-x: hidden;
  }
}
</style>
